import './public-path';
import { createApp } from 'vue';
import App from './App.vue';
import 'ant-design-vue/dist/antd.css';
import { setupRouter } from './router';
import store from './store';
import '@/assets/styles/base/tailwind.css';
import initPlugins from '@/plugins';
import TjDesign from 'tj-design-vue';
import 'tj-design-vue/lib/index.css';
import '/src/util/iconfont';
import '/src/util/iconfont.css';
// 在main.js中全局引入
import VideoPlayer from 'vue-video-player/src';
import 'vue-video-player/src/custom-theme.css';
import 'video.js/dist/video-js.css';
// svg图标组件
import SvgIcon from './components/svgIcon';

const { changeThemeColor } = require('./util/theme');
// import { checkCurrentUserIsAdmin } from './api/user';

let history;
let router;
let app;
let antd;
// 用于应用每次初始化时 判断当前是否属于被缓存状态，也就是说子应用只有第一次被加载时才会发送请求解析子应用
// 以后每次切换子应用都是从js的缓存中直接读取
// 除非 micro-app的destroy是true的情况下 每次切换子应用都会重新加载资源进行初始化
let isCached = false;

function mount() {
  const { router: _router, history: _history } = setupRouter();
  history = _history;
  router = _router;
  app = createApp(App);
  initPlugins(app);
  app.use(store);
  app.use(antd);
  app.use(router);
  app.use(TjDesign);
  app.use(VideoPlayer);
  app.mount('#micro-app-info-system');
  // console.log('main');
  // 全局组件
  app.component('SvgIcon', SvgIcon);

  if (window.__MICRO_APP_ENVIRONMENT__) {
    // 全局监听函数
    window.microApp.addGlobalDataListener(({ data, methods, appName } = {}) => {
      console.log(data, '数据');
      if (appName === 'microBaseApp') {
        window.$microAppMethods = methods;
        if (data.token) {
          store.commit('user/setTokens', data.token);
          localStorage.setItem('tokenToken', data.token);
        }
        // 接受的主题颜色
        if (data.primaryColor) {
          changeThemeColor(data.primaryColor);
          document.documentElement.style.setProperty(
            '--tj-primary-color-4',
            set16ToRgb(data.primaryColor, 0.5)
          );
          document.documentElement.style.setProperty('--tj-primary-color', data.primaryColor);
          document.documentElement.style.setProperty('--themecolor', data.primaryColor);
          document.documentElement.style.setProperty(
            '--themecolorhover',
            set16ToRgb(data.primaryColor, 0.5)
          );
          document.documentElement.style.setProperty(
            '--themecolor5',
            set16ToRgb(data.primaryColor, 0.5)
          );
          document.documentElement.style.setProperty(
            '--themecolor02',
            set16ToRgb(data.primaryColor, 0.2)
          );
          store.commit('user/setPrimaryColor', data.primaryColor);
        } else {
          changeThemeColor(data.primaryColor);
          store.commit('user/setPrimaryColor', '#11afaf');
        }
        // 传值问问张良轩
      }
    }, true);

    // 独立的监听函数 监听当前自身（子应用）与基座的通信
    window.microApp.addDataListener((data = {}) => {
      if (isCached && data.path) {
        setTimeout(() => {
          router.push(data.path);
        });
      }
      if (data.appData.applicationId) {
        // store.commit('user/applicationId', data.appData.applicationId);
        localStorage.setItem('applicationId', data.appData.applicationId);
      }
      if (data.appId) {
        store.commit('user/appId', data.appId);
        localStorage.setItem('appId', data.appId);
      }
    }, true);
  } else {
    // 本地开发数据
    changeThemeColor('#34b07c');
    document.documentElement.style.setProperty('--tj-primary-color-4', set16ToRgb('#34b07c', 0.5));
    document.documentElement.style.setProperty('--tj-primary-color', '#34b07c');
    document.documentElement.style.setProperty('--themecolor', '#34b07c');
    document.documentElement.style.setProperty('--themecolorhover', set16ToRgb('#34b07c', 0.5));
    document.documentElement.style.setProperty('--themecolor02', set16ToRgb('#34b07c', 0.2));
    document.documentElement.style.setProperty('--themecolor5', set16ToRgb('#34b07c', 0.5));
    store.commit('user/setPrimaryColor', '#34b07c');
    store.commit('user/appId', '481774449444556800');
    localStorage.setItem('appId', '481774449444556800');
    let data = {
      user: {
        mainOrganizeId: '346946249091543040',
        mainSchoolId: '346946249116708865',
        businessId: '346944991718895616',
        username: '张三',
        email: '',
        mobile: '15053850605',
        sex: 1,
        nation: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        province: '',
        city: '',
        area: '',
        address: '',
        idCardType: 0,
        idCard: '37091119950120243X',
        authentication: 1,
        birthDate: 790531200000,
        nickName: '马端飞',
        avatar:
          'https://saas-resource.obs.cn-east-3.myhuaweicloud.com/tenant/2022-11-21/16689970778191659001388569v2-ff6e65d3cfe92a4f3df9e1bc41asdasdasdasdasdasdasdec81dc_720w.jpg',
        lastLoginTime: 1692322239000
      },
      parent: {
        businessId: '426017818052395009',
        tenantId: '346946249091543040',
        schoolBusinessId: '346946249116708865',
        userBusinessId: '346944991718895616',
        avatar: ''
      },
      teacher: {
        businessId: '346957362415890432',
        tenantId: '346946249091543040',
        schoolBusinessId: '346946249116708865',
        userBusinessId: '346944991718895616',
        avatar: '',
        photo: '',
        campusCard: '1156338875'
      },
      schoolInfo: {
        isMainSchool: false,
        mainSchoolId: 0,
        schoolId: '346946249116708865',
        organizeId: '346946249091543040',
        schoolName: '自测组织开发专用',
        schoolLogo:
          'https://saas-resource.obs.cn-east-3.myhuaweicloud.com/tenant/2022-8-11/1660211691374v2-ff6e65d3cfe92a4f3df9e1bc41ec81dc_720w.jpg',
        organizeName: '自测组织开发专用'
      },
      isAdmin: 1,
      identities: [3, 2, 1]
    };
    localStorage.setItem('allUser', JSON.stringify(data));
  }
}
function set16ToRgb(str, num) {
  let reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
  if (!reg.test(str)) {
    return;
  }
  let newStr = str.toLowerCase().replace(/\#/g, '');
  let len = newStr.length;
  if (len === 3) {
    let t = '';
    for (let i = 0; i < len; i++) {
      t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1));
    }
    newStr = t;
  }
  let arr = []; // 将字符串分隔，两个两个的分隔
  for (let i = 0; i < 6; i = i + 2) {
    let s = newStr.slice(i, i + 2);
    arr.push(parseInt('0x' + s));
  }
  return 'rgb(' + arr.join(',') + ',' + num + ')';
}

function unmount() {
  app.unmount();
  history.destroy();
  history = null;
  router = null;
  app = null;
  isCached = true;
  window.microApp.clearGlobalDataListener();
}

if (window.__MICRO_APP_ENVIRONMENT__) {
  initMicroApp();
} else {
  mount();
}

function initMicroApp() {
  window[`micro-app-${window.__MICRO_APP_NAME__}`] = {
    mount,
    unmount
  };
}
